package util

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/gogf/gf/container/glist"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"net/http"
	"runtime"
)

func GetPath() string {
	path_windows := "C:\\Windows\\System32\\drivers\\etc\\hosts"
	path_linux := "/etc/hosts"
	path := ""
	system := runtime.GOOS
	switch system {
	case "windows":
		{
			path = path_windows
			break
		}
	case "linux":
		{
			path = path_linux
			break
		}
	case "darwin":
		{
			path = path_linux
			break
		}
	}
	return path
}
func UpdateHOST(domain, ip string) {
	domain = gstr.ToLower(domain)
	path := GetPath()
	if gfile.Exists(path) {
		//删除已有映射 start
		lines_new := glist.New(true)
		lines_back := glist.New(true)
		gfile.ReadLines(path, func(line string) {
			//备份原内容
			lines_back.PushBack(line)
			//这分隔判断规则只保障程序自动加入的映射关系
			if len(line) == 0 {
				//完全空白行不保留
			} else if gstr.Contains(line, " ") {
				lineTemp := gstr.Split(line, " ")[1]

				if gstr.Equal(domain, lineTemp) {
					//找到存在的
				} else {
					if gstr.Contains(line, "\n") {
						lines_new.PushBack(line)
					} else {
						lines_new.PushBack(line + "\n")
					}
				}
			} else {
				if gstr.Contains(line, "\n") {
					lines_new.PushBack(line)
				} else {
					lines_new.PushBack(line + "\n")
				}
			}
		})
		//删除已有映射 end
		lines_new.PushBack("\n" + ip + " " + domain)
		//清空文件
		gfile.PutContents(path, "")

		lines_new.Iterator(func(e *glist.Element) bool {
			gfile.PutContentsAppend(path, gconv.String(e.Value))
			return true
		})

		//fmt.Println("更新HOSTS成功", gfile.GetContents(path))
	} else {
		glog.Error("没有找到系统HOSTS文件")
	}

}

// 从ipaddress.com获取最快IP
func GetIp(domain string) (string, error) {
	dotNum := gstr.Count(domain, ".")

	if dotNum == 0 {
		//不是合法域名
		return "", gerror.New("非法域名")
	} else if dotNum == 1 {
		//baidu.com
		domain = fmt.Sprintf("https://%s.ipaddress.com", domain)
	} else {
		//a.b.c.d  :    c.d    a.b.c.c
		domainArray := gstr.Split(domain, ".")
		temp := domainArray[len(domainArray)-2] + "." + domainArray[len(domainArray)-1]
		domain = fmt.Sprintf("https://%s.ipaddress.com/%s", temp, domain)
	}
	glog.Debug("domain:", domain)
	res, err := http.Get(domain)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		return "", err
	} else {
		doc, err := goquery.NewDocumentFromReader(res.Body)
		if err != nil {
			return "", err
		}

		fastIp := ""
		doc.Find(".table-stripes").First().Find("tr").Each(func(i int, s *goquery.Selection) {
			fmt.Println(i, " ", s.Find("th").Text())
			if gstr.ContainsI(s.Find("th").Text(), "IPv4") {
				fastIp = s.Find("td>ul>li").First().Text()
			}
		})
		fmt.Println(fastIp)
		return fastIp, nil
	}
}
func ReadHosts() string {
	contents := gfile.GetContents(GetPath())
	return contents
}
